import request from "./request";
import type { CreatePostParams, Post } from "../types";

/**
 * 创建帖子
 * @param data 帖子数据
 * @returns 创建的帖子信息
 */
export const createPost = async (data: CreatePostParams): Promise<Post> => {
  const response = await request.post("/api/posts", data);
  return response.data;
};

/**
 * 获取帖子列表
 * @param params 查询参数
 * @returns 帖子列表
 */
export const getPostList = async (params: {
  category?: string;
  page?: number;
  pageSize?: number;
  keyword?: string;
  sortBy?: string;
}): Promise<{ data: Post[]; total: number }> => {
  const response = await request.get("/api/posts", { params });
  return response.data;
};

/**
 * 获取帖子详情
 * @param id 帖子ID
 * @returns 帖子详情
 */
export const getPostDetail = async (id: string): Promise<Post> => {
  const response = await request.get(`/api/posts/${id}`);
  return response.data;
};

/**
 * 更新帖子
 * @param id 帖子ID
 * @param data 更新的数据
 * @returns 更新后的帖子信息
 */
export const updatePost = async (
  id: string,
  data: Partial<CreatePostParams>
): Promise<Post> => {
  const response = await request.put(`/api/posts/${id}`, data);
  return response.data;
};

/**
 * 删除帖子
 * @param id 帖子ID
 * @returns 删除结果
 */
export const deletePost = async (id: string): Promise<void> => {
  await request.delete(`/api/posts/${id}`);
};

/**
 * 点赞帖子
 * @param id 帖子ID
 * @returns 点赞后的数量
 */
export const likePost = async (id: string): Promise<number> => {
  const response = await request.post(`/api/posts/${id}/like`);
  return response.data.likes;
};

/**
 * 收藏帖子
 * @param id 帖子ID
 * @returns 收藏结果
 */
export const favoritePost = async (id: string): Promise<void> => {
  await request.post(`/api/posts/${id}/favorite`);
};

/**
 * 上传图片
 * @param file 图片文件
 * @returns 图片URL
 */
export const uploadImage = async (file: File): Promise<string> => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await request.post("/api/upload/image", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });

  return response.data.url;
};
